package com.xzmd.md_city.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xzmd.md_city.entity.User;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author:Corday
 * @Date:2021/09/12/22:10
 */
public class MyJson {
    //////////////1.字符串解析为对象////////////////////
    public static void jsonToObject() {//解析复杂的JSON字符串对象
        String us = "{'add':'纽约大街','u':{'uid':101,'name':'tom','age':19},'arr':[{'name':'tom','age':19},{'name':'bean','age':20}]}";
        JSONObject obj = JSONObject.parseObject(us);
        //(1)取出字符串
        String add = obj.getObject("add", String.class);
        //String add=obj.get("add").toString();
        System.out.println("add:" + add);
        //(2)取出一个实体对象
        User u = obj.getObject("u", User.class);
        System.out.println("姓名:" + u.getName() + " 年龄:" + u.getAge());
        //(3)取出一个JSON数组对象
        JSONArray arr = obj.getJSONArray("arr");//再转成字符串
        List<User> list = JSON.parseObject(arr.toString(), new TypeReference<List<User>>() {});
        for (User t : list) {
            System.out.println(" 姓名：" + t.getName() + " 年龄：" + t.getAge());
        }
    }
////2.java对象转换成JSON字符串对象
    public static  void objectToJSON(){
        //(1)普通对象转换成JSON字符串
        User user=new User(1006,"小江",19);
        String str=JSON.toJSONString(user);
        System.out.println(str);
        //(2)集合对象转换成JSON字符串
        List<User> list=new ArrayList<>();
        list.add(new User(1001,"小美",19));
        list.add(new User(1003,"小红",18));
        list.add(new User(1002,"小帅",20));
        String strs=JSON.toJSONString(list);
        System.out.println(strs);
        //(3)日期对象转换成JSON字符串,并设置输出格式
        Date date = new Date();
        //按字段名称排序后输出,默认为false;HH/hh(24小时制/12小时制)
        String dstr=JSON.toJSONStringWithDateFormat(date,"yyyy-MM-dd HH:mm:ss",SerializerFeature.SortField);
        System.out.println(dstr);
    }

    public static void main(String[] args) {
        //jsonToObject();
        objectToJSON();
    }
}
